package com.iflysse.utils;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Random;

public class CommonUtil {

	/**
	 * 生成随机验证码
	 * @param len 验证码长度
	 * @return
	 */
	public static String genCode(int len) {
//		TODO 请完善此方法，生成指定长度的纯数字随机验证码
		Random r =new Random();
		
		return ""+(r.nextInt(9000)+1000);
	}

	
	/**
	 * 拼接base64码输出到前端
	 * 
	 * @param base
	 * @param type
	 * @throws IOException
	 */
	public static String appendBaseToWebApp(String base, String type) throws IOException {
		String prefix = "data:image/";
		String suffix = ";base64,";
		String result = prefix + type + suffix + base;
		return result;
	}
	
	
	/**
     * 类型转换工具   VO转BO ，BO转PO  相同属性可转 ，不同属性手动set
     * @param source
     * @param targetClazz
     * @param <T>
     * @return
     */
    public static <T>T objToObj(Object source, Class<T> targetClazz) {
        try {
            T target = targetClazz.newInstance();
            Class sourceClazz = source.getClass();

            Field[] sourceFields = sourceClazz.getDeclaredFields();
            Field[] targetFields = target.getClass().getDeclaredFields();

            for (Field sourceField : sourceFields) {
                sourceField.setAccessible(true);
                for (Field targetField : targetFields) {
                    if (targetField.getName().equals(sourceField.getName()) && targetField.getType() == sourceField.getType()) {
                        int mod = targetField.getModifiers();
                        if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                            continue;
                        }
                        targetField.setAccessible(true);
                        targetField.set(target, sourceField.get(source));
                        break;
                    }
                }
            }
            return target;
        }catch (Exception e){
            return null;
        }
    }


}

